package com.snowleopard.findpeople.web;

import java.util.Map;

import org.apache.struts2.interceptor.RequestAware;
import org.apache.struts2.interceptor.SessionAware;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;
import com.snowleopard.common.security.CurrentUser;

/**
 * Struts2中典型CRUD Action的抽象基类.
 * 
 * 主要定义了对Preparable,ModelDriven接口的使用,以及CRUD函数和返回值的命名.
 * 
 * @author LiuJian
 */
public abstract class CrudActionSupport<T> extends ActionSupport implements ModelDriven<T>,
        Preparable, RequestAware, SessionAware {

    private static final long serialVersionUID = -1653204626115064950L;

    private final static Logger log = LoggerFactory.getLogger(CrudActionSupport.class);

    public static final String LOGIN_ID = "loginId";

    /** 进行增删改操作后,以redirect方式重新打开action默认页的result名. */
    public static final String RELOAD = "reload";

    /**
     * Action函数, 默认的action函数, 默认调用list()函数.
     */
    @Override
    public String execute() throws Exception {
        return list();
    }

    // -- CRUD Action函数 --//
    /**
     * Action函数,显示Entity列表界面. 建议return SUCCESS.
     */
    public abstract String list() throws Exception;

    /**
     * Action函数,显示新增或修改Entity界面. 建议return INPUT.
     */
    @Override
    public abstract String input() throws Exception;

    /**
     * Action函数,新增或修改Entity. 建议return RELOAD.
     */
    public abstract String save() throws Exception;

    /**
     * Action函数,删除Entity. 建议return RELOAD.
     */
    public abstract String delete() throws Exception;

    /** ******************** HPP add page parameters *********************START */
    protected Map<String, Object> request;
    protected Map<String, Object> session;

    public void setRequest(Map<String, Object> request) {
        this.request = request;

    }

    public void setSession(Map<String, Object> session) {
        this.session = session;
    }

    /** ******************** HPP add page parameters *********************START */

    // -- Preparable函数 --//

    /**
     * 实现空的prepare()函数,屏蔽了所有Action函数都会执行的公共的二次绑定.
     * 
     * @see com.opensymphony.xwork2.Preparable#prepare()
     */
    public void prepare() throws Exception {
        log.info("************ Prepare common parameters for page ***************START");

        // 1. Store login id to session for jsp.
        if (!this.session.containsKey(LOGIN_ID)) {
            session.put(LOGIN_ID, CurrentUser.getName());
        }

        log.info("************ Prepare common parameters for page ***************END");
    }

}
